package com.roger.tool.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.xmlpull.v1.XmlPullParser;

import android.content.Context;
import android.util.Xml;

/**
 * 获取基地渠道信息
 * @author lch
 *
 */
public class JdChannelParser {

	/**
	 * 获取基地渠道名称
	 * 
	 * @param pContext
	 * @return
	 */
	public static String getJdChannelName(Context pContext) {

		InputStream mInputStream = readJdChannelConfigFromAssets(pContext);

		return getValue(mInputStream, "channelName");
	}

	/**
	 * 获取基地渠道ID
	 * 
	 * @param pContext
	 * @return
	 */
	public static String getJdChannelId(Context pContext) {

		InputStream mInputStream = readJdChannelConfigFromAssets(pContext);

		return getValue(mInputStream, "channelId");
	}

	/**
	 * 读取基地的 渠道配置 xml
	 * 
	 * @param pContext
	 * @return
	 */
	public static InputStream readJdChannelConfigFromAssets(Context pContext) {

		InputStream mInputStream = null;
		try {
			mInputStream = pContext.getAssets().open("CHANNEL" + File.separator + "channel.xml");
		} catch (IOException e) {
		}

		return mInputStream;
	}

	public static String getValue(InputStream xmlInputStream, String name) {

		if (xmlInputStream == null || name == null) {
			return "";
		}

		XmlPullParser parser = Xml.newPullParser();
		String value = null;
		try {
			parser.setInput(new InputStreamReader(xmlInputStream));
			int eventype = parser.getEventType();
			while (eventype != XmlPullParser.END_DOCUMENT) {
				switch (eventype) {
				case XmlPullParser.START_TAG:
					if (parser.getName().equalsIgnoreCase(name))
						value = parser.nextText();
					break;
				}
				eventype = parser.next();
			}
		} catch (Exception e) {

		}
		
		if(value == null){
			value = "";
		}
		
		return value;
	}

}
